import React, { useEffect, useRef, useState } from 'react';
import { Attachments, Bubble, useXAgent, useXChat } from '@ant-design/x';
import { createStyles } from 'antd-style';
import { Link, useModel } from '@umijs/max';
import { Button, Spin, type GetProp } from 'antd';
import { BACKEND_HOST } from '../../constants';
import './index.css';
import './markdown.css';
import { v4 as uuidv4 } from 'uuid';
import { EventSourcePolyfill } from 'event-source-polyfill';

// 导入组件
import Sidebar from './components/Sidebar';
import ChatMain from './components/ChatMain';
import FileUploader from './components/FileUploader';

const defaultConversationsItems = [
  {
    key: '0',
    label: 'Jira Knowledge',
  },
];

// 样式定义
const useStyle = createStyles(({ token, css }) => {
  return {
    layout: css`
      width: 100%;
      min-width: 1000px;
      height: 100vh;
      border-radius: ${token.borderRadius}px;
      display: flex;
      background: ${token.colorBgContainer};
      font-family: AlibabaPuHuiTi, ${token.fontFamily}, sans-serif;
      overflow: hidden;

      .ant-prompts {
        color: ${token.colorText};
      }
    `,
    menu: css`
      background: ${token.colorBgLayout}80;
      width: 280px;
      height: 100%;
      display: flex;
      flex-direction: column;
      overflow: hidden;
    `,
    conversations: css`
      padding: 0 12px;
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
    `,
    chat: css`
      height: 100%;
      width: 100%;
      max-width: 700px;
      margin: 0 auto;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      padding: ${token.paddingLG}px;
      gap: 16px;
      overflow: hidden;
    `,
    messages: css`
      flex: 1;
      overflow-y: auto;
      overflow-x: hidden;
    `,
    placeholder: css`
      padding-top: 32px;
    `,
    sender: css`
      box-shadow: ${token.boxShadow};
    `,
    logo: css`
      display: flex;
      height: 72px;
      align-items: center;
      justify-content: start;
      padding: 0 24px;
      box-sizing: border-box;

      img {
        width: 24px;
        height: 24px;
        display: inline-block;
      }

      span {
        display: inline-block;
        margin: 0 8px;
        font-weight: bold;
        color: ${token.colorText};
        font-size: 16px;
      }
    `,
    addBtn: css`
      background: #1677ff0f;
      border: 1px solid #1677ff34;
      width: calc(100% - 24px);
      margin: 0 12px 24px 12px;
    `,
  };
});

const Independent: React.FC = () => {
  // 样式
  const { styles } = useStyle();

  // 状态
  const [headerOpen, setHeaderOpen] = useState(false);
  const [content, setContent] = useState('');
  const [conversationsItems, setConversationsItems] = useState(defaultConversationsItems);
  const [activeKey, setActiveKey] = useState(defaultConversationsItems[0].key);
  const [attachedFiles, setAttachedFiles] = useState<GetProp<typeof Attachments, 'items'>>([]);
  const [uploading, setUploading] = useState(false);
  // 添加会话ID状态
  const [sessionMemoryIds, setSessionMemoryIds] = useState<Record<string, string>>({});

  const abortRef = useRef(() => {});

  // 添加一个useEffect来监控sessionMemoryIds的变化
  useEffect(() => {
    console.log('当前会话记忆ID映射:', sessionMemoryIds);
  }, [sessionMemoryIds]);

  useEffect(() => {
    return () => {
      abortRef.current();
    };
  }, []);

  // Agent 设置
  const [agent] = useXAgent({
    request: async ({ message }, { onSuccess, onUpdate, onError }) => {
      try {
        let fullContent = '';

        // 检查当前会话是否已有memoryId，如果没有则创建新的
        let memoryId = sessionMemoryIds[activeKey];
        if (!memoryId) {
          memoryId = uuidv4();
          console.log(`为会话 ${activeKey} 创建新的memoryId: ${memoryId}`);
          setSessionMemoryIds((prev) => ({
            ...prev,
            [activeKey]: memoryId,
          }));
        } else {
          console.log(`使用会话 ${activeKey} 的已有memoryId: ${memoryId}`);
        }

        const eventSource = new EventSourcePolyfill(
          `${BACKEND_HOST}/api/chat/agentChat?userMessage=${encodeURIComponent(
            message ?? '',
          )}&memoryId=${encodeURIComponent(memoryId)}`,
          {
            withCredentials: true,
          },
        );

        // const eventSource = new EventSource(
        //   `${BACKEND_HOST}/api/chat/memory_stream_chat_sse?message=${encodeURIComponent(
        //     message ?? '',
        //   )}`,
        // );
        eventSource.onmessage = async (event) => {
          console.log('Received: ', event.data);
          if (event.data === '[DONE]') {
            onSuccess(fullContent);
            eventSource.close();
          } else {
            fullContent += event.data;
            onUpdate(fullContent);
          }
        };

        eventSource.onerror = (error) => {
          console.error('SSE Error:', error);
          eventSource.close();
        };
      } catch (err) {
        // @ts-ignore
        onError(`SSE连接异常: ${err.message}`);
        console.error(err);
      }
    },
  });

  const { onRequest, messages, setMessages } = useXChat({
    agent,
  });

  useEffect(() => {
    if (activeKey !== undefined) {
      setMessages([]);
    }
  }, [activeKey]);

  // 从localStorage加载会话记忆ID
  useEffect(() => {
    const savedSessionMemoryIds = localStorage.getItem('sessionMemoryIds');
    if (savedSessionMemoryIds) {
      try {
        setSessionMemoryIds(JSON.parse(savedSessionMemoryIds));
      } catch (e) {
        console.error('解析保存的会话记忆ID失败:', e);
      }
    }
  }, []);

  // 保存会话记忆ID到localStorage
  useEffect(() => {
    if (Object.keys(sessionMemoryIds).length > 0) {
      localStorage.setItem('sessionMemoryIds', JSON.stringify(sessionMemoryIds));
    }
  }, [sessionMemoryIds]);

  const items: GetProp<typeof Bubble.List, 'items'> = messages.map(({ id, message, status }) => ({
    key: id,
    loading: status === 'loading',
    role: status === 'local' ? 'local' : 'ai',
    content: message,
  }));

  // 提交消息
  const onSubmit = (nextContent: string) => {
    if (!nextContent) return;
    onRequest(nextContent);
    setContent('');
  };

  // 文件上传组件
  const { attachmentsNode, senderHeader } = FileUploader({
    headerOpen,
    setHeaderOpen,
    attachedFiles,
    setAttachedFiles,
    uploading,
    setUploading,
  });

  // 获取当前用户
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};

  if (!currentUser) {
    return (
      <Link to="/user/login">
        <Button type="primary" shape="round">
          L
        </Button>
      </Link>
    );
  }

  const contentStyle = {
    padding: 50,
    background: 'rgba(0, 0, 0, 0.05)',
    borderRadius: 4,
  };

  const loadingContent = <div style={contentStyle} />;

  return (
    <div className={styles.layout}>
      <Spin tip="Loading" fullscreen spinning={uploading}>
        {loadingContent}
      </Spin>

      {/* 侧边栏 */}
      <Sidebar
        styles={styles}
        conversationsItems={conversationsItems}
        setConversationsItems={setConversationsItems}
        activeKey={activeKey}
        setActiveKey={setActiveKey}
      />

      {/* 聊天主体 */}
      <ChatMain
        styles={styles}
        content={content}
        setContent={setContent}
        items={items}
        onSubmit={onSubmit}
        senderHeader={senderHeader}
        attachmentsNode={attachmentsNode}
        isAgentRequesting={agent.isRequesting()}
        onCancel={() => abortRef.current()}
      />
    </div>
  );
};

export default Independent;
